using System;
using System.Workflow.Activities;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Text;
using NETL.Engine.Data;
using log4net;

namespace NETL.Engine.Source
{
	public abstract class MessageSourceBase : IMessageSource
	{
		private ILog myLogger;
		private string myName;
		private string myDescription;

		public event MessageReceived Received;

		public event ReceiveError Error;

		public event SourceStopped Stopped;

		public event SourceStarted Started;

		public event EventHandler<ExternalDataEventArgs> Foo;

		public string Name
		{
			get { return myName; }
			set { myName = value; }
		}

		public string Description
		{
			get { return myDescription; }
			set { myDescription = value; }
		}

		[XmlIgnore]
		protected ILog Logger
		{
			get { return myLogger; }
		}

		public MessageSourceBase()
		{
			myLogger = LogManager.GetLogger(GetType());
		}

		public abstract void Start();
		public abstract void Stop();
		public abstract ExecutionResult Test();

		protected void OnStarted()
		{
			if (Logger.IsInfoEnabled)
			{
				Logger.InfoFormat("Started {0}", myName);
			}

			SourceStarted tmp = Started;
			if (tmp != null)
			{
				tmp(this);
			}
		}

		protected void OnStopped()
		{
			if (Logger.IsInfoEnabled)
			{
				Logger.InfoFormat("Stopped {0}", myName);
			}

			SourceStopped tmp = Stopped;
			if (tmp != null)
			{
				tmp(this);
			}
		}

		protected void OnReceived(IMessage message)
		{
			if (Logger.IsInfoEnabled)
			{
				Logger.InfoFormat("Received message {0}", message);
			}

			MessageReceived tmp = Received;
			if (tmp != null)
			{
				tmp(this, message);
			}
		}

		protected void OnError(ExecutionResult result)
		{
			if (Logger.IsErrorEnabled)
			{
				Logger.Error(String.Format("Error {0}", result.Message), result.Exception);
			}

			ReceiveError tmp = Error;
			if (tmp != null)
			{
				tmp(this, result);
			}
		}

	}
}
